package com.yangguang.huahui.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;


import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.model.EaseDefaultEmojiconDatas;
import com.hyphenate.easeui.utils.EaseSmileUtils;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 表情转textview内容
 * Created by ${liangsz} on 2016/11/25.
 */
public class EmojiToText {
    private static Pattern buildPattern() {
        StringBuilder patternString = new StringBuilder(EaseDefaultEmojiconDatas.emojis.length * 3);
        patternString.append('(');
        for (String s : EaseDefaultEmojiconDatas.emojis) {
            patternString.append(Pattern.quote(s));
            patternString.append('|');
        }
        patternString.replace(patternString.length() - 1,
                patternString.length(), ")");
        return Pattern.compile(patternString.toString());
    }

    private static HashMap<String, Integer> buildSmileyToRes() {
        /**
         * 文字和ID不匹配，异常
         */
        if (EaseDefaultEmojiconDatas.icons.length != EaseDefaultEmojiconDatas.emojis.length) {
            throw new IllegalStateException("Smiley resource ID/text mismatch");
        }
        HashMap<String, Integer> smileyToRes = new HashMap<String, Integer>(
                EaseDefaultEmojiconDatas.emojis.length);
        for (int i = 0; i < EaseDefaultEmojiconDatas.emojis.length; i++) {
            smileyToRes.put(EaseDefaultEmojiconDatas.emojis[i], EaseDefaultEmojiconDatas.icons[i]);
        }
        return smileyToRes;
    }

    @SuppressWarnings("deprecation")
    public static CharSequence addSmileySpans(Context context, CharSequence text) {
        Pattern pattern = buildPattern();
        HashMap<String, Integer> faceBook = buildSmileyToRes();
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            int resId = faceBook.get(matcher.group());
            Drawable dr = context.getResources().getDrawable(resId);
            dr.setBounds(0, 0, dr.getIntrinsicWidth()*4/5, dr.getIntrinsicHeight()*4/5);
            builder.setSpan(new ImageSpan(dr, ImageSpan.ALIGN_BOTTOM),
                    matcher.start(), matcher.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return builder;
    }
}
